<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    width="90%"
    @close="reset"
  >
    <!-- 添加步骤 -->
    <a-steps label-placement="vertical" :current="currentStep">
      <a-step v-for="(step, index) in steps" :key="index" :title="step.title" />
    </a-steps>

    <!-- 表单 -->
    <a-form
      ref="formRef"
      v-loading="fullscreenLoading"
      style="margin-top: 20px; height: 600px"
      :rules="ruleValidate"
      :model="formValidate"
      label-col="{ span: 6 }"
      wrapper-col="{ span: 18 }"
      @submit.native.prevent
    >
      <a-row v-show="currentStep === 1" :gutter="24">
        <!-- 商品信息 -->
        <a-col :span="12">
          <a-form-item label="商品名称：" field="storeName">
            <a-input
              v-model="formValidate.storeName"
              maxlength="249"
              placeholder="请输入商品名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="商品分类：" field="cateIds">
            <a-cascader
              v-model="formValidate.cateIds"
              :options="merCateList"
              :field-names="{
                children: 'children',
                label: 'name',
                value: 'id',
              }"
              check-strictly
              allow-clear
              :show-all-levels="false"
              multiple
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="商品关键字：" field="keyword">
            <a-input
              v-model="formValidate.keyword"
              placeholder="请输入商品关键字"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="单位：" field="unitName">
            <a-input v-model="formValidate.unitName" placeholder="请输入单位" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="商品简介：" field="storeInfo">
            <a-textarea
              v-model="formValidate.storeInfo"
              maxlength="250"
              rows="3"
              placeholder="请输入商品简介"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12"> </a-col>
        <a-col :span="12">
          <a-form-item label="商品封面图：" field="image">
            <a-upload
              :file-list="productList"
              accept="image/*"
              :show-file-list="false"
              list-type="picture-card"
              :show-upload-button="true"
              :on-before-upload="onBeforeUpload"
            >
              <template #upload-button>
                <div v-if="formValidate.image" class="pictrue">
                  <img :src="formValidate.image" />
                </div>
                <div v-else class="upLoad">
                  <icon-camera :style="{ fontSize: '32px' }" />
                </div>
              </template>
            </a-upload>
            <a-tag style="margin-left: 5px" color="orange"
              >上传封面图不得大于5MB</a-tag
            >
          </a-form-item>
        </a-col>
        <a-col :span="12"> </a-col>
        <a-col :span="12">
          <a-form-item label="商品轮播图：" field="sliderImages">
            <a-upload
              :file-list="productSlidersList"
              accept="image/*"
              list-type="picture-card"
              :show-upload-button="true"
              image-preview
              :limit="5"
              @change="addProductSliders"
            >
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="12"> </a-col>
        <a-col :span="12">
          <a-form-item label="运费模板：" field="tempId">
            <a-select
              v-model="formValidate.tempId"
              placeholder="请选择"
              class="mr20"
              :disabled="isDisabled"
              style="width: 100%"
            >
              <a-option
                v-for="item in shippingList"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <!-- <a-button v-show="!isDisabled" class="mr15" @click="addTem"
            >运费模板</a-button
          > -->
        </a-col>
        <a-col :span="12">
          <a-form-item label="商品规格：" field="specType">
            <a-radio-group
              v-model="formValidate.specType"
              @change="onChangeSpec(formValidate.specType)"
              :disabled="isDisabled"
            >
              <a-radio :value="false" class="radio">单规格</a-radio>
              <!-- <a-radio :value="true">多规格</a-radio> -->
            </a-radio-group>
          </a-form-item>
          <a-form-item label="佣金设置：" field="isSub">
            <a-radio-group
              v-model="formValidate.isSub"
              :disabled="isDisabled"
            >
              <a-radio :value="true" class="radio">单独设置</a-radio>
              <a-radio :value="false">默认设置</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-col :span="12">
            <!-- 单规格表格 -->
            <a-form-item>
              <a-table
                v-if="!formValidate.specType"
                :data="formValidate.attrValue"
                size="small"
                row-key="id"
                :scroll="{ x: '100%', y: '100%', minWidth: 800 }"
                :bordered="false"
                :pagination="false"
              >
                <template #columns>
                  <a-table-column title="图片" :min-width="120">
                    <template #cell="{ record }">
                      <a-upload
                        accept="image/*"
                        :show-file-list="false"
                        list-type="picture-card"
                        :show-upload-button="true"
                        @change="(info) => addSingleAttrImage(info, record)"
                      >
                        <template #upload-button>
                          <div v-if="record.image" class="pictrue">
                            <img :src="record.image" />
                          </div>
                          <div v-else class="upLoad">
                            <icon-camera :style="{ fontSize: '32px' }" />
                          </div>
                        </template>
                      </a-upload>
                    </template>
                  </a-table-column>

                  <a-table-column title="售价" :min-width="120">
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.price"
                        :step="0.01"
                        :min="0.01"
                        :precision="2"
                        :max="999999999"
                      />
                    </template>
                  </a-table-column>

                  <a-table-column title="成本价" :min-width="120">
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.cost"
                        :step="0.01"
                        :min="0.01"
                        :precision="2"
                        :max="999999999"
                      />
                    </template>
                  </a-table-column>
                  <a-table-column title="原价" :min-width="120">
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.otPrice"
                        :step="0.01"
                        :min="0.01"
                        :precision="2"
                        :max="999999999"
                      />
                    </template>
                  </a-table-column>
                  <a-table-column title="库存" :min-width="120">
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.stock"
                        :step="1"
                        :min="1"
                        :max="999999999"
                      />
                    </template>
                  </a-table-column>
                  <a-table-column title="商品编号" :min-width="120">
                    <template #cell="{ record }">
                      <a-input v-model="record.barCode" />
                    </template>
                  </a-table-column>

                  <a-table-column title="重量（KG）" :min-width="120">
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.weight"
                        :step="0.01"
                        :min="0.01"
                        :precision="2"
                        :max="999999999"
                      />
                    </template>
                  </a-table-column>

                  <a-table-column title="体积(m³)" :min-width="120">
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.volume"
                        :step="0.01"
                        :min="0.01"
                        :precision="2"
                        :max="999999999"
                      />
                    </template>
                  </a-table-column>

                  <template v-if="formValidate.isSub">
                    <a-table-column title="一级返佣(元)" :min-width="120">
                      <template #cell="{ record }">
                        <a-input-number
                          v-model="record.brokerage"
                          :step="1"
                          :min="1"
                        />
                      </template>
                    </a-table-column>
                    <a-table-column title="二级返佣(元)" :min-width="120">
                      <template #cell="{ record }">
                        <a-input-number
                          v-model="record.brokerageTwo"
                          :step="1"
                          :min="1"
                        />
                      </template>
                    </a-table-column>
                  </template>
                </template>
              </a-table>
            </a-form-item>
          </a-col>
        </a-col>

        <a-col :span="24">
          <!-- 多规格表格 -->
          <a-form-item
            v-if="formValidate.attr.length > 0 && formValidate.specType"
            label="商品属性："
          >
            <!-- <a-table
              :data="ManyAttrValue"
              bordered
              size="small"
              class="tabNumWidth"
            >
              <template v-if="manyTabDate">
                <a-table-column
                  v-for="(item, iii) in manyTabDate"
                  :key="iii"
                  :title="manyTabTit[iii].title"
                  align="center"
                  :min-width="80"
                >
                  <template #cell="{ record }">
                    <span class="priceBox">{{ record[iii] }}</span>
                  </template>
                </a-table-column>
              </template>
              <a-table-column title="图片" :min-width="80" align="center">
                <template #cell="{ record }">
                  <div @click="modalPicTap('1', 'duo', record.$index)">
                    <div v-if="record.image" class="pictrue tabPic">
                      <img :src="record.image" />
                    </div>
                    <div v-else class="upLoad tabPic">
                      <i class="icon-camera cameraIconfont" />
                    </div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column
                v-for="(item, iii) in attrValue"
                :key="iii"
                :title="formThead[iii].title"
                align="center"
                :min-width="120"
              >
                <template #cell="{ record }">
                  <a-input
                    :disabled="isDisabled"
                    maxlength="9"
                    min="0.01"
                    v-model="record[iii]"
                    class="priceBox"
                    @blur="keyupEvent(iii, record[iii], record, 3)"
                  />
                </template>
              </a-table-column>
              <a-table-column
                title="一级返佣(元)"
                :min-width="120"
                align="center"
                v-if="formValidate.isSub"
              >
                <template #cell="{ record }">
                  <a-input
                    :disabled="isDisabled"
                    v-model="record.brokerage"
                    type="number"
                    :min="0"
                    :max="record.price"
                    class="priceBox"
                  />
                </template>
              </a-table-column>
              <a-table-column
                title="二级返佣(元)"
                :min-width="120"
                align="center"
                v-if="formValidate.isSub"
              >
                <template #cell="{ record }">
                  <a-input
                    :disabled="isDisabled"
                    v-model="record.brokerageTwo"
                    type="number"
                    :min="0"
                    :max="record.price"
                    class="priceBox"
                  />
                </template>
              </a-table-column>
              <a-table-column
                title="操作"
                :min-width="80"
                align="center"
                v-if="!isDisabled"
              >
                <template #cell="{ record }">
                  <a-button
                    type="text"
                    class="submission"
                    @click="delAttrTable(record.$index)"
                    >删除</a-button
                  >
                </template>
              </a-table-column>
            </a-table> -->
          </a-form-item>
        </a-col>

        <!-- 多规格添加-->
        <!-- <a-col :span="24">
          <a-col
            v-if="formValidate.specType && !isDisabled"
            :span="12"
            class="noForm"
          >
            <a-form-item label="选择规格：">
              <div class="acea-row">
                <a-select v-model="formValidate.selectRule">
                  <a-option
                    v-for="item in ruleList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.ruleName }}
                  </a-option>
                </a-select>
                <a-button type="primary" class="mr20" @click="confirm"
                  >确认</a-button
                >
                <a-button class="mr15" @click="addRule">添加规格</a-button>
              </div>
            </a-form-item>
            <a-form-item>
              <div v-for="(item, index) in formValidate.attr" :key="index">
                <div class="acea-row row-middle">
                  <span class="mr5">{{ item.attrName }}</span>
                </div>
                <div class="rulesBox">
                  <a-tag
                    v-for="(j, indexn) in item.attrValue"
                    :key="indexn"
                    closable
                    size="medium"
                    :disable-transitions="false"
                    class="mb5 mr10"
                    @close="handleClose(item.attrValue, indexn)"
                  >
                    {{ j }}
                  </a-tag>
                  <a-input
                    v-if="item.inputVisible"
                    ref="saveTagInput"
                    v-model="item.attrValue.attrsVal"
                    class="input-new-tag"
                    size="small"
                    @keyup.enter.native="
                      createAttr(item.attrValue.attrsVal, index)
                    "
                    @blur="createAttr(item.attrValue.attrsVal, index)"
                  />
                  <a-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(item)"
                  >
                    + 添加
                  </a-button>
                </div>
              </div>
            </a-form-item>
            <a-col v-if="isBtn">
              <a-col :xl="6" :lg="9" :md="9" :sm="24" :xs="24">
                <a-form-item label="规格：">
                  <a-input
                    v-model="formDynamic.attrsName"
                    placeholder="请输入规格"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="9" :md="9" :sm="24" :xs="24">
                <a-form-item label="规格值：">
                  <a-input
                    v-model="formDynamic.attrsVal"
                    placeholder="请输入规格值"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="12" :lg="6" :md="6" :sm="24" :xs="24">
                <a-form-item class="noLeft">
                  <a-button type="primary" class="mr15" @click="createAttrName"
                    >确定</a-button
                  >
                  <a-button @click="offAttrName">取消</a-button>
                </a-form-item>
              </a-col>
            </a-col>
            <a-form-item v-if="!isBtn">
              <a-button type="primary" icon="plus" class="mr15" @click="addBtn"
                >添加新规格</a-button
              >
            </a-form-item>
          </a-col>
        </a-col> -->

        <!-- 批量设置-->
        <!-- <a-col :span="24">
          <a-col
            v-if="
              formValidate.attr.length > 0 &&
              formValidate.specType &&
              !isDisabled
            "
            :span="24"
            class="noForm"
          >
            <a-form-item label="批量设置：">
              <a-table
                :data="oneFormBatch"
                border
                size="mini"
                class="tabNumWidth"
              >
                <a-table-column align="center" title="图片" :width="80">
                  <template #cell="{ record }">
                    <div @click="modalPicTap('1', 'pi')">
                      <div v-if="record.image" class="pictrue tabPic">
                        <img :src="record.image" />
                      </div>
                      <div v-else class="upLoad tabPic">
                        <i class="icon icon-camera cameraIconfont" />
                      </div>
                    </div>
                  </template>
                </a-table-column>

                <a-table-column
                  v-for="(item, iii) in attrValue"
                  :key="iii"
                  align="center"
                  :width="120"
                >
                  <template #cell="{ record }">
                    <a-input
                      v-model="record[iii]"
                      :maxLength="9"
                      :min="0.01"
                      @blur="keyupEvent(iii, record[iii], record.index, 1)"
                    />
                  </template>
                </a-table-column>

                <template v-if="formValidate.isSub">
                  <a-table-column
                    title="一级返佣(元)"
                    align="center"
                    :width="120"
                  >
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.brokerage"
                        :min="0"
                        :max="record.price"
                      />
                    </template>
                  </a-table-column>

                  <a-table-column
                    title="二级返佣(元)"
                    align="center"
                    :width="120"
                  >
                    <template #cell="{ record }">
                      <a-input-number
                        v-model="record.brokerageTwo"
                        :min="0"
                        :max="record.price"
                      />
                    </template>
                  </a-table-column>
                </template>

                <a-table-column align="center" title="操作" :width="80">
                  <template #cell="{ record }">
                    <a-button type="text" class="submission" @click="batchAdd"
                      >批量添加</a-button
                    >
                  </template>
                </a-table-column>
              </a-table>
            </a-form-item>
          </a-col>
        </a-col> -->
      </a-row>
      <!-- 商品详情 -->
      <a-row v-show="currentStep === 2" :gutter="24">
        <a-col :span="12">
          <a-form-item label="商品详情：" field="content"> </a-form-item>
        </a-col>
        <a-col :span="12"> </a-col>
        <a-col :span="24">
          <!-- {{ formValidate.content }}
          <a-input v-model="formValidate.content"></a-input> -->
          <quill-editor
            v-model:content="formValidate.editorContent"
            :options="editorOptions"
            ref="myQuillEditor"
          ></quill-editor>
        </a-col>
      </a-row>
      <!-- 其他设置 -->
      <a-row v-show="currentStep === 3" :gutter="24">
          <a-col :span="12">
            <a-form-item label="排序：">
              <a-input-number
                v-model="formValidate.sort"
                :min="0"
                placeholder="请输入排序"
                :disabled="isDisabled"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="积分：">
              <a-input-number
                v-model="formValidate.giveIntegral"
                :min="0"
                placeholder="请输入积分"
                :disabled="isDisabled"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="虚拟销量：">
              <a-input-number
                v-model="formValidate.ficti"
                :min="0"
                placeholder="请输入虚拟销量"
                :disabled="isDisabled"
              />
            </a-form-item>
          </a-col>

        <a-col :span="24">
          <!-- <a-form-item label="商品推荐：">
            <a-checkbox-group
              v-model="checkboxGroup"
              size="small"
              @change="onChangeGroup"
              :disabled="isDisabled"
            >
              <a-checkbox
                v-for="(item, index) in recommend"
                :key="index"
                :value="item.value"
                >{{ item.name }}</a-checkbox
              >
            </a-checkbox-group>
          </a-form-item> -->
        </a-col>

        <!-- <a-col :span="24">
          <a-form-item label="活动优先级：">
            <div class="color-list acea-row row-middle">
              <div
                :disabled="isDisabled"
                class="color-item"
                :class="activity[item].color"
                v-for="item in formValidate.activity"
                :key="item"
                draggable="true"
                @dragstart="handleDragStart($event, item)"
                @dragover.prevent="handleDragOver($event, item)"
                @dragenter="handleDragEnterFont($event, item)"
                @dragend="handleDragEnd($event, item)"
              >
                {{ item }}
              </div>
              <div class="tip">可拖动按钮调整活动的优先展示顺序</div>
            </div>
          </a-form-item>
        </a-col> -->

        <a-col :span="24">
          <!-- <a-form-item label="优惠券：" class="proCoupon">
            <div class="acea-row">
              <a-tag
                v-for="(tag, index) in formValidate.coupons"
                :key="index"
                class="mr10 mb10"
                closable
                @close="handleCloseCoupon(tag)"
              >
                {{ tag.name }}
              </a-tag>
              <a-button v-if="!isDisabled" class="mr15" @click="addCoupon"
                >选择优惠券</a-button
              >
            </div>
          </a-form-item> -->
        </a-col>
      </a-row>
    </a-form>

    <template v-slot:footer>
      <a-button type="outline" @click="prevStep" v-show="currentStep > 1"
        >上一步</a-button
      >
      <a-button
        type="outline"
        @click="nextStep"
        v-show="currentStep < steps.length"
        >下一步</a-button
      >
      <a-button
        type="primary"
        @click="save"
        v-show="currentStep === steps.length"
        >提交</a-button
      >
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { type FileItem, Message } from "@arco-design/web-vue";
import {
  getStoreProduct,
  addStoreProduct,
  updateStoreProduct,
  treeCategory,
  getAllShippingTemplates,
  getAllStoreProductRules,
  type CategoryResp,
} from "@/apis";
import { useForm } from "@/hooks";
import { useDict } from "@/hooks/app";
import { type Columns, GiForm, type Options } from "@/components/GiForm";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";

const emit = defineEmits<{
  (e: "save-success"): void;
}>();

const dataId = ref("");
const isUpdate = computed(() => !!dataId.value);
const title = computed(() => (isUpdate.value ? "修改商品" : "新增商品"));
const formRef = ref<FormInstance>();

const formValidate = reactive({
  image: "",
  sliderImages: [],
  videoLink: "",
  sliderImage: "",
  storeName: "",
  storeInfo: "",
  keyword: "",
  cateIds: [], // 商品分类id
  cateId: "", // 商品分类id传值
  unitName: "",
  sort: 0,
  giveIntegral: 0,
  ficti: 0,
  isShow: false,
  isBenefit: false,
  isNew: false,
  isGood: false,
  isHot: false,
  isBest: false,
  tempId: "",
  attrValue: [
    {
      image: "",
      price: 0,
      cost: 0,
      otPrice: 0,
      stock: 0,
      barCode: "",
      weight: 0,
      volume: 0,
      brokerage: 0,
      brokerageTwo: 0,
    },
  ],
  attr: [],
  selectRule: "",
  isSub: false,
  content: "",
  editorContent: "",
  specType: false,
  id: 0,
  couponIds: [],
  coupons: [],
  // "默认", "秒杀", "砍价", "拼团"
  activity: [0, 1, 2, 3],
});

const isDisabled = ref(false);

const activity = reactive([
  {
    color: "red",
    title: "默认",
    id: "default",
  },
  {
    color: "blue",
    title: "秒杀",
    id: "secKill",
  },
  {
    color: "green",
    title: "砍价",
    id: "dePrice",
  },
  {
    color: "yellow",
    title: "拼团",
    id: "groupBuy",
  },
]);

const fileRef = ref(reactive({ name: "avatar.png" }));
const productList = ref<FileItem[]>([]);
const onBeforeUpload = (file: File): boolean => {
  fileRef.value = file;
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    formValidate.image = reader.result;
  };
  visible.value = true;
  return false;
};

const productSlidersList = ref<FileItem[]>([]);
// 处理文件变化
const addProductSliders = (fileList: any) => {
  // 将文件列表的 originFile 赋值给 formData.files
  formValidate.sliderImages = fileList.map((item: any) => item.url);
};

const editorOptions = {
  placeholder: "请输入商品详情...",
  theme: "snow",
  readOnly: false,  // 确保不是只读模式
  modules: {
    toolbar: [
      ["bold", "italic", "underline"], // 加粗、斜体、下划线
      [{ header: 1 }, { header: 2 }], // 标题1，标题2
      [{ list: "ordered" }, { list: "bullet" }], // 有序列表，无序列表
      [{ align: [] }], // 文本对齐
      ["image", "link"], // 图片、链接
    ], // 自定义工具栏
  },
};

const myQuillEditor = ref();  // 不需要初始化为 null，Vue 会自动绑定 Quill 实例
    
// const onEditorChange = ()=>{
  
//   // formValidate.content = this.$refs.myQuillEditor.quill.root.innerHTML; // 手动更新 v-model
//   if (myQuillEditor.value) {
//     // 通过 Quill 实例获取当前内容
//     const delta = myQuillEditor.value.getContents();
//     formValidate.content = JSON.stringify(delta);
//   }
// }

const attrValue = reactive({
  image: "",
  price: 0,
  cost: 0,
  otPrice: 0,
  stock: 0,
  barCode: "",
  weight: 0,
  volume: 0,
});

const oneFormBatch = reactive({
  image: "",
  price: 0,
  cost: 0,
  otPrice: 0,
  stock: 0,
  weight: 0,
  volume: 0,
});

const fullscreenLoading = ref(false);

const ManyAttrValue = reactive([
  {
    image: "",
    price: 0,
    cost: 0,
    otPrice: 0,
    stock: 0,
    weight: 0,
    volume: 0,
  },
]);

const ruleList = ref<any[]>([]);
const merCateList = ref<any[]>([]);
const shippingList = ref<any[]>([]);
const formThead = reactive({
  image: { title: "图片" },
  price: { title: "售价" },
  cost: { title: "成本价" },
  otPrice: { title: "原价" },
  stock: { title: "库存" },
  barCode: { title: "商品编号" },
  weight: { title: "重量（KG）" },
  volume: { title: "体积(m³)" },
});


const manyTabTit = reactive({});
const manyTabDate = reactive({});

const ruleValidate = {
  storeName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  cateIds: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
      type: "array",
      min: "1",
    },
  ],
  keyword: [{ required: true, message: "请输入商品关键字", trigger: "blur" }],
  unitName: [{ required: true, message: "请输入单位", trigger: "blur" }],
  storeInfo: [{ required: true, message: "请输入商品简介", trigger: "blur" }],
  tempId: [{ required: true, message: "请选择运费模板", trigger: "change" }],
  image: [{ required: true, message: "请上传商品图", trigger: "change" }],
  sliderImages: [
    {
      required: true,
      message: "请上传商品轮播图",
      type: "array",
      trigger: "change",
    },
  ],
  specType: [{ required: true, message: "请选择商品规格", trigger: "change" }],
};

const attrInfo = reactive({});

const isAttr = ref(false);

const addSingleAttrImage = (info: any, record: any) => {
  record.image = info[0].url;
};

interface AttrItem {
  attrName: string;
  attrValue: Record<string, any>;
}
// 方法
const handleAttr = (val: any) => {
  const tmp: Record<string, { title: string }> = {};
  const tmpTab: Record<string, string> = {};

  // 遍历 formValidate.attr 并生成 tmp 和 tmpTab 对象
  formValidate.attr.forEach((o: AttrItem, i: number) => {
    tmp[o.attrName] = { title: o.attrName };
    tmpTab[o.attrName] = "";
  });

  // 格式化属性值
  ManyAttrValue.splice(0, ManyAttrValue.length, ...attrFormat(val));

  // 更新 ManyAttrValue 中的值，如果属性已经存在于 attrInfo 中则使用该值
  ManyAttrValue.forEach((val, index) => {
    const key = Object.values(val.attrValue).sort().join("/");
    if (attrInfo[key]) {
      ManyAttrValue[index] = attrInfo[key];
    }
  });

  // 清空 attrInfo
  for (const key in attrInfo) {
    delete attrInfo[key];
  }

  // 重新构建 attrInfo
  ManyAttrValue.forEach((val) => {
    attrInfo[Object.values(val.attrValue).sort().join("/")] = val;
  });

  // 更新表头和数据
  Object.assign(manyTabTit, tmp);
  Object.assign(manyTabDate, tmpTab);
  Object.assign(formThead, tmp);
};

interface Attr {
  attrName: string;
  attrValue: string[];
}

interface AttrResult {
  image: string;
  price: number;
  cost: number;
  otPrice: number;
  stock: number;
  barCode: string;
  weight: number;
  volume: number;
  brokerage: number;
  brokerage_two: number;
  attrValue: Record<string, string>;
}

const attrFormat = (arr: Attr[]): AttrResult[] => {
  if (arr.length === 0) return [];

  const res: AttrResult[] = [];

  const processSingleAttr = (arr: Attr[]): AttrResult[] => {
    const res: AttrResult[] = [];
    const dataArr: string[] = [];
    arr.forEach((v) => {
      v.attrValue.forEach((vv, kk) => {
        dataArr[kk] = `${v.attrName}_${vv}`;
        const attrResult: AttrResult = {
          image: "",
          price: 0,
          cost: 0,
          otPrice: 0,
          stock: 0,
          barCode: "",
          weight: 0,
          volume: 0,
          brokerage: 0,
          brokerage_two: 0,
          attrValue: { [v.attrName]: vv },
        };
        res[kk] = attrResult;
      });
    });
    dataArr.push(dataArr.join("$&"));
    return res;
  };

  const processMultipleAttrs = (arr: Attr[]): AttrResult[] => {
    const tmp: string[] = [];
    let data: string[] = arr[0].attrValue || [];

    arr.forEach((v, i) => {
      if (i > 0) {
        const newTmp: string[] = [];
        data.forEach((vv) => {
          arr[i + 1]?.attrValue?.forEach((g) => {
            const rep2 =
              (i !== 0 ? "" : `${arr[i].attrName}_`) +
              `${vv}$&${arr[i + 1].attrName}_${g}`;
            newTmp.push(rep2);
            if (i === arr.length - 2) {
              const attrResult: AttrResult = {
                image: "",
                price: 0,
                cost: 0,
                otPrice: 0,
                stock: 0,
                barCode: "",
                weight: 0,
                volume: 0,
                brokerage: 0,
                brokerage_two: 0,
                attrValue: {},
              };
              rep2.split("$&").forEach((h) => {
                const [key, value] = h.split("_");
                attrResult.attrValue[key] = value || "";
              });
              for (const key in attrResult.attrValue) {
                attrResult[key] = attrResult.attrValue[key];
              }
              res.push(attrResult);
            }
          });
        });
        data = newTmp.length ? newTmp : [];
      }
    });

    return res;
  };

  return arr.length > 1 ? processMultipleAttrs(arr) : processSingleAttr(arr);
};

// 监控 formValidate.attr 的变化
watch(
  () => formValidate.attr,
  (val) => {
    if (formValidate.specType && isAttr) {
      handleAttr(val); // 重要的逻辑
    }
  },
  {
    immediate: false, // 默认不立即执行
    deep: true, // 深度监控
  }
);

// 生命周期钩子 - 组件挂载后执行
onMounted(() => {
  formValidate.sliderImages = [];

  // 编辑的逻辑
  // if (route.params.id) {
  //   setTagsViewTitle();
  //   getInfo();
  // }

  if (isUpdate.value) {
  }

  getCategorySelect();
  getShippingList();
  // getGoodsType();

});

// 切换规格
const onChangeSpec = (num) => {
  isAttr.value = true;
  if (num) {
    getProductRule();
  }
};

// 获取运费模板
const getProductRule = async () => {
  const res = await getAllStoreProductRules();
  for (let i = 0; i < res.data.length; i++) {
    res.data[i].ruleValue = JSON.parse(res.data[i].ruleValue);
  }
  ruleList.value = res.data;
};

// 获取运费模板
const getShippingList = async () => {
  const res = await getAllShippingTemplates();
  shippingList.value = res.data;
};

// 获取商品分类选择
const getCategorySelect = async () => {
  const _pram = reactive({ type: "1", status: "-1", name: "" });
  const res = await treeCategory(_pram);
  // 过滤商品分类设置为隐藏的子分类不出现在树形列表里
  const newArr = res.data.map((value) => {
    const newItem = { ...value };
    if (value.children) {
      newItem.children = value.children.filter((item) => item.status === true);
    }
    return newItem;
  });

  // 更新商品分类列表
  merCateList.value = filterMerCateList(newArr);
};

const filterMerCateList = (treeData: any[]): any[] => {
  return treeData.map((item: any) => {
    if (!item.children) {
      item.disabled = true; // 没有子分类时禁用该分类
    }
    item.label = item.name; // 将 name 赋值给 label 用于展示
    return item;
  });
};

const currentStep = ref(1);

const steps = ref([
  { title: "商品信息" },
  { title: "商品详情" },
  { title: "其他设置" },
]);

const nextStep = () => {
  if (currentStep.value < steps.value.length) {
    currentStep.value += 1;
  }
};

const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value -= 1;
  }
};

const { form, resetForm } = useForm({
  // todo 待补充
});

// 重置
const reset = () => {
  formRef.value?.resetFields();
  resetForm();
};

const visible = ref(false);
// 新增
const onAdd = () => {
  reset();
  dataId.value = "";
  visible.value = true;
};

// 修改
const onUpdate = async (id: string) => {
  reset();
  dataId.value = id;
  const res = await getStoreProduct(id);
  Object.assign(form, res.data);
  visible.value = true;
};

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.validate();
    if (isInvalid) return false;
    if (isUpdate.value) {
      await updateStoreProduct(formValidate);
      Message.success("修改成功");
    } else {
      formValidate.content = JSON.stringify(formValidate.editorContent)
      formValidate.sliderImage = JSON.stringify(formValidate.sliderImages)
      formValidate.cateId = formValidate.cateIds.join(',')
      await addStoreProduct(formValidate);
      Message.success("新增成功");
    }
    emit("save-success");
    return true;
  } catch (error) {
    return false;
  }
};


defineExpose({ onAdd, onUpdate });
</script>

<style scoped lang="scss">
.priamry_border {
  border: 1px solid #1890ff;
  color: #1890ff;
}
.color-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #fff;
  margin-right: 10px;
}
.color-list .color-item.blue {
  background-color: #1e9fff;
}
.color-list .color-item.yellow {
  background-color: rgb(254, 185, 0);
}
.color-list .color-item.green {
  background-color: #009688;
}
.color-list .color-item.red {
  background-color: #ed4014;
}
.tabPic {
  width: 40px !important;
  height: 40px !important;
  img {
    width: 100%;
    height: 100%;
  }
}
.selWidth {
  width: 100%;
}
.selWidthd {
  width: 300px;
}
.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
  }
  video {
    width: 100%;
    height: 100%;
  }
}
.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  left: 46px;
  top: -4px;
}
.iview-video-style {
  width: 300px;
  height: 180px;
  border-radius: 10px;
  background-color: #707070;
  margin: 0 120px 20px;
  position: relative;
  overflow: hidden;
}

.iview-video-style .iconv {
  color: #fff;
  line-height: 180px;
  width: 50px;
  height: 50px;
  display: inherit;
  font-size: 26px;
  position: absolute;
  top: -74px;
  left: 50%;
  margin-left: -25px;
}

.iview-video-style .mark {
  position: absolute;
  width: 100%;
  height: 30px;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;
}

:deep(.ql-editor){
  height: 500px;
}
</style>
